package com.android.clinic.doctors.app.http.utils;

import com.android.clinic.doctors.app.ui.widget.dialog.LoadingDialog;

import java.util.concurrent.TimeUnit;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by cheng on 2018/6/19.
 */
public class RxObservableUtils {

    /**
     * 无进度Schedulers
     */
    public static <T> ObservableTransformer<T, T> applySchedulers() {
        return upstream -> upstream
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 有进度Schedulers
     */
    public static <T> ObservableTransformer<T, T> applySchedulers(@NonNull final LoadingDialog dialog, final String title) {
        return upstream -> upstream
                .delay(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    dialog.setOnCancelListener(dialog1 -> disposable.dispose());
                    dialog.show();
                    dialog.setTitle(title);
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doOnTerminate(new Action() {
                    @Override
                    public void run() throws Exception {
                        dialog.dismiss();
                    }
                });
    }

}
